package com.jinzhi.common.filter;

import com.github.wxpay.sdk.WXPayUtil;
import com.jinzhi.common.configconsts.wxconsts.LinkConfiggure;
import com.jinzhi.common.vo.WxPayConfig;
import com.jinzhi.common.vo.WxPayVo;
import com.jinzhi.common.utils.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信链路之组装参数
 */
@Slf4j
@Component
public class WxAssembleFilter implements Command {

	@Autowired
	private WxPayConfig wxPayConfig;

	@Override
	public boolean execute(Context context) throws Exception {

		log.info("链路:微信支付执行到:组装参数");

		//获取支付对象
		WxPayVo wxPayVo = (WxPayVo) context.get(LinkConfiggure.WX_PAY_VO);
		//获取返回对象
		ApiResult apiResult = (ApiResult) context.get(LinkConfiggure.API_RESULT);

		//组装微信支付参数Map
		Map<String, String> requestMap = new HashMap<String, String>();

		try{
			//JSAPI支付 openId不能为空
			if (LinkConfiggure.TRADE_TYPE_JSAPI.equals(wxPayVo.getTrade_type())) {
				if (StringUtils.isEmpty(wxPayVo.getOpenId())){
					apiResult.setCode(LinkConfiggure.WX_ERROR_CODE);
					apiResult.setMsg("openId不能为空");
					return true;
				}
				requestMap.put("openid", wxPayVo.getOpenId());
			}

			//固定参数
			requestMap.put("appid", wxPayVo.getAppid());
			requestMap.put("mch_id", wxPayVo.getMch_id());
			requestMap.put("spbill_create_ip", wxPayVo.getSpbill_create_ip());
			requestMap.put("notify_url", wxPayVo.getNotify_url());
			requestMap.put("out_trade_no", wxPayVo.getOut_trade_no());
			requestMap.put("nonce_str", wxPayVo.getNonce_str());

			log.info("wxPayVo.getTotal_fee()=="+wxPayVo.getTotal_fee());
			//组装参数
			requestMap.put("body", wxPayVo.getBody());
			requestMap.put("total_fee", wxPayVo.getTotal_fee());
			requestMap.put("trade_type", wxPayVo.getTrade_type());

			//判断attach是否为空（防止拼接参数生成sign时 出现空指针异常）
			if (!StringUtils.isEmpty(wxPayVo.getAttach())){
				requestMap.put("attach",wxPayVo.getAttach());
			}

			String mySign = WXPayUtil.generateSignature(requestMap,
					wxPayConfig.getMerSecret());

			requestMap.put("sign", mySign);
			log.info("当前requestMap为:{}", requestMap);

			//将Map保存至上下文中
			context.put(LinkConfiggure.REQUEST_MAP,requestMap);
		}catch (Exception e){
			apiResult.setCode(LinkConfiggure.WX_ERROR_CODE);
			apiResult.setMsg("组装Map失败");
			return true;
		}

		return false;
	}
}
